package xyz.lne.researchgroupmanage.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import xyz.lne.researchgroupmanage.annotation.AnonymousGetMapping;
import xyz.lne.researchgroupmanage.annotation.AnonymousPostMapping;
import xyz.lne.researchgroupmanage.common.CommonResponse;
//import xyz.lne.researchgroupmanage.common.accountGenerator;
import xyz.lne.researchgroupmanage.common.generater;
import xyz.lne.researchgroupmanage.controller.request.ResearchRequest;
import xyz.lne.researchgroupmanage.controller.request.UserApplyResearchRequest;
import xyz.lne.researchgroupmanage.controller.response.*;
import xyz.lne.researchgroupmanage.entity.Research;
import xyz.lne.researchgroupmanage.entity.UserResearch;
import xyz.lne.researchgroupmanage.exception.BadRequestException;
import xyz.lne.researchgroupmanage.exception.BadTokenException;
import xyz.lne.researchgroupmanage.security.UserPower;
import xyz.lne.researchgroupmanage.service.*;
import xyz.lne.researchgroupmanage.service.dataTransferObject.*;
import xyz.lne.researchgroupmanage.util.SecurityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Result;
import java.util.*;

import static xyz.lne.researchgroupmanage.security.UserPower.RESEARCH_MANAGE;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author team7
 * @since 2021-01-19
 */
@RestController
@RequestMapping("/research")
public class ResearchController {

    @Autowired
    ResearchService researchService;

    @Autowired
    DocumentService documentService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    TaskService taskService;

    @Autowired
    UserResearchService userResearchService;

    @Autowired
    KeywordResearchService keywordResearchService;

    @Autowired
    FileService fileService;

    /**
     * 查看所有课题
     *
     * @return
     */
    @AnonymousGetMapping(value = "/listAll")
    public CommonResponse listAll() {
        List<ResearchSimpleDTO> researchSimpleDTOS = researchService.findAllResearch();

        List<ResearchSimpleResponse> researchSimpleResponses = new LinkedList<>();

        researchSimpleDTOS.forEach(researchSimpleDTO -> {
            if (researchSimpleDTO.getResearchId() != 0) {
                ResearchSimpleResponse researchSimpleResponse = new ResearchSimpleResponse();
                BeanUtils.copyProperties(researchSimpleDTO, researchSimpleResponse);
                researchSimpleResponses.add(researchSimpleResponse);
            }
        });

        return CommonResponse.create(researchSimpleResponses);
    }

    /**
     * 查看我管理的课题
     *
     * @return
     */
    @AnonymousGetMapping(value = "/managelist")
    public CommonResponse manageList() {
        List<ResearchSimpleDTO> researchSimpleDTOS = researchService.findResearchBymanagerId(SecurityUtils.getCurrentUserId());

        List<ResearchSimpleResponse> researchSimpleResponses = new LinkedList<>();

        researchSimpleDTOS.forEach(researchSimpleDTO -> {
            if (researchSimpleDTO.getResearchId() != 0) {
                ResearchSimpleResponse researchSimpleResponse = new ResearchSimpleResponse();
                BeanUtils.copyProperties(researchSimpleDTO, researchSimpleResponse);
                researchSimpleResponses.add(researchSimpleResponse);
            }
        });

        return CommonResponse.create(researchSimpleResponses);
    }

    /**
     * 查看我加入的课题
     *
     * @return
     */
    @AnonymousGetMapping(value = "/joinlist")
    public CommonResponse joinList() {
        List<ResearchSimpleDTO> researchSimpleDTOS = researchService.findResearchByuserId(SecurityUtils.getCurrentUserId());

        List<ResearchSimpleResponse> researchSimpleResponses = new LinkedList<>();

        researchSimpleDTOS.forEach(researchSimpleDTO -> {
            if (researchSimpleDTO.getResearchId() != 0) {
                ResearchSimpleResponse researchSimpleResponse = new ResearchSimpleResponse();
                BeanUtils.copyProperties(researchSimpleDTO, researchSimpleResponse);
                researchSimpleResponses.add(researchSimpleResponse);
            }
        });

        return CommonResponse.create(researchSimpleResponses);
    }

    /**
     * 查看课题具体信息
     *
     * @param researchId
     * @return
     */
    @AnonymousGetMapping(value = "/detail")
    public CommonResponse researchdetail(@RequestParam("researchId") Integer researchId) {
        ResearchResponse researchResponse = new ResearchResponse();

        ResearchNormalResponse researchNormalResponse = new ResearchNormalResponse();
        List<UserApplyResearchResponse> userApplyResearchResponses = new LinkedList<>();

        researchResponse.setResearchNormalResponse(researchNormalResponse);
        researchResponse.setUserApplyResearchResponseList(userApplyResearchResponses);

        List<UserResearchDTO> userResearchDTOS = userResearchService.findUsersByresearch(researchId);
        List<Integer> userIds = new LinkedList<>();
        userResearchDTOS.forEach(userResearchDTO -> {
            userIds.add(userResearchDTO.getUserId());
        });
        List<UserDTO> userDTOS = sysUserService.getUsersById(userIds);
        Map<Integer, String> userid_name = new HashMap<>();
        userDTOS.forEach(userDTO -> {
            userid_name.put(userDTO.getUserId(), userDTO.getName());
        });

        List<DocumentSimpleResponse> documentSimpleResponses = new LinkedList<>();

        List<DocumentSimpleDTO> documentDTOS = documentService.findDocumentSimpleByResearchId(researchId);

        documentDTOS.forEach(documentSimpleDTO -> {
            DocumentSimpleResponse documentSimpleResponse = new DocumentSimpleResponse();
            BeanUtils.copyProperties(documentSimpleDTO, documentSimpleResponse);
            documentSimpleResponses.add(documentSimpleResponse);
        });

        List<TaskSimpleResponse> taskSimpleResponses = new LinkedList<>();

        List<TaskSimpleDTO> taskDTOS = taskService.getAllTasksByResearchId(researchId);

        taskDTOS.forEach(taskSimpleDTO -> {
            TaskSimpleResponse taskSimpleResponse = new TaskSimpleResponse();
            BeanUtils.copyProperties(taskSimpleDTO, taskSimpleResponse);
            taskSimpleResponses.add(taskSimpleResponse);
        });

        ResearchDTO researchDTO = researchService.findResearchNormalById(researchId);

        BeanUtils.copyProperties(researchDTO, researchNormalResponse);
        researchNormalResponse.setTaskSimpleResponseList(taskSimpleResponses);
        researchNormalResponse.setDocumentSimpleResponseList(documentSimpleResponses);
        researchNormalResponse.setUserName(sysUserService.getById(researchDTO.getUserId()).getName());

        userResearchDTOS.forEach(userResearchDTO -> {
            UserApplyResearchResponse userApplyResearchResponse = new UserApplyResearchResponse();
            BeanUtils.copyProperties(userResearchDTO, userApplyResearchResponse);
            userApplyResearchResponses.add(userApplyResearchResponse);
        });

        return CommonResponse.create(researchResponse);
    }

    /**
     * 新增课题
     *
     * @param researchRequest
     * @return
     */
    @AnonymousPostMapping(value = "/add")
    public CommonResponse addresearch(@RequestBody ResearchRequest researchRequest) {
        Research research = new Research();

        research.setName(researchRequest.getName());
        research.setIntroduction(researchRequest.getIntroduction());
        research.setIsHide(researchRequest.getIsHide());
        research.setJoinStatus(0);
        research.setCreateDate(new Date());
        research.setResearchImg(researchRequest.getResearchImg());
        research.setUserId(SecurityUtils.getCurrentUserId());
        research.setResearchgroupId(0);
        research.setIsDissolve(false);
        research.setAccount(generater.accountGenerator(2));
        research.setJoinGroupTime(new Date());

        try {
            researchService.addResearch(research);

            Integer researchId = research.getResearchId();

            ResearchResponse researchResponse = new ResearchResponse();

            ResearchNormalResponse researchNormalResponse = new ResearchNormalResponse();
            List<UserApplyResearchResponse> userApplyResearchResponses = new LinkedList<>();

            researchResponse.setResearchNormalResponse(researchNormalResponse);
            researchResponse.setUserApplyResearchResponseList(userApplyResearchResponses);

            List<UserResearchDTO> userResearchDTOS = userResearchService.findUsersByresearch(researchId);
            List<Integer> userIds = new LinkedList<>();
            userResearchDTOS.forEach(userResearchDTO -> {
                userIds.add(userResearchDTO.getUserId());
            });
            List<UserDTO> userDTOS = sysUserService.getUsersById(userIds);
            Map<Integer, String> userid_name = new HashMap<>();
            userDTOS.forEach(userDTO -> {
                userid_name.put(userDTO.getUserId(), userDTO.getName());
            });

            List<DocumentSimpleResponse> documentSimpleResponses = new LinkedList<>();

            List<DocumentSimpleDTO> documentDTOS = documentService.findDocumentSimpleByResearchId(researchId);

            documentDTOS.forEach(documentSimpleDTO -> {
                DocumentSimpleResponse documentSimpleResponse = new DocumentSimpleResponse();
                BeanUtils.copyProperties(documentSimpleDTO, documentSimpleResponse);
                documentSimpleResponses.add(documentSimpleResponse);
            });

            List<TaskSimpleResponse> taskSimpleResponses = new LinkedList<>();

            List<TaskSimpleDTO> taskDTOS = taskService.getAllTasksByResearchId(researchId);

            taskDTOS.forEach(taskSimpleDTO -> {
                TaskSimpleResponse taskSimpleResponse = new TaskSimpleResponse();
                BeanUtils.copyProperties(taskSimpleDTO, taskSimpleResponse);
                taskSimpleResponses.add(taskSimpleResponse);
            });

            ResearchDTO researchDTO = researchService.findResearchNormalById(researchId);

            BeanUtils.copyProperties(researchDTO, researchNormalResponse);
            researchNormalResponse.setTaskSimpleResponseList(taskSimpleResponses);
            researchNormalResponse.setDocumentSimpleResponseList(documentSimpleResponses);

            userResearchDTOS.forEach(userResearchDTO -> {
                UserApplyResearchResponse userApplyResearchResponse = new UserApplyResearchResponse();
                BeanUtils.copyProperties(userResearchDTO, userApplyResearchResponse);
                userApplyResearchResponses.add(userApplyResearchResponse);
            });

            return CommonResponse.create(researchResponse);
        } catch (BadTokenException badTokenException) {
            badTokenException.printStackTrace();
        }
        return CommonResponse.Failed();
    }

    /**
     * 更新课题
     *
     * @param researchRequest
     * @return
     */
    @AnonymousPostMapping(value = "/update")
    public CommonResponse updateResearch(@RequestBody ResearchRequest researchRequest) {
        Research research = new Research();

        research.setResearchId(researchRequest.getResearchId());
        research.setIntroduction(researchRequest.getIntroduction());
        research.setIsHide(researchRequest.getIsHide());
        research.setResearchImg(researchRequest.getResearchImg());
        research.setName(researchRequest.getName());
        research.setIsDissolve(false);

        try {
            researchService.updateResearch(research);

            Integer researchId = research.getResearchId();

            ResearchResponse researchResponse = new ResearchResponse();

            ResearchNormalResponse researchNormalResponse = new ResearchNormalResponse();
            List<UserApplyResearchResponse> userApplyResearchResponses = new LinkedList<>();

            researchResponse.setResearchNormalResponse(researchNormalResponse);
            researchResponse.setUserApplyResearchResponseList(userApplyResearchResponses);

            List<UserResearchDTO> userResearchDTOS = userResearchService.findUsersByresearch(researchId);
            List<Integer> userIds = new LinkedList<>();
            userResearchDTOS.forEach(userResearchDTO -> {
                userIds.add(userResearchDTO.getUserId());
            });
            List<UserDTO> userDTOS = sysUserService.getUsersById(userIds);
            Map<Integer, String> userid_name = new HashMap<>();
            userDTOS.forEach(userDTO -> {
                userid_name.put(userDTO.getUserId(), userDTO.getName());
            });

            List<DocumentSimpleResponse> documentSimpleResponses = new LinkedList<>();

            List<DocumentSimpleDTO> documentDTOS = documentService.findDocumentSimpleByResearchId(researchId);

            documentDTOS.forEach(documentSimpleDTO -> {
                DocumentSimpleResponse documentSimpleResponse = new DocumentSimpleResponse();
                BeanUtils.copyProperties(documentSimpleDTO, documentSimpleResponse);
                documentSimpleResponses.add(documentSimpleResponse);
            });

            List<TaskSimpleResponse> taskSimpleResponses = new LinkedList<>();

            List<TaskSimpleDTO> taskDTOS = taskService.getAllTasksByResearchId(researchId);

            taskDTOS.forEach(taskSimpleDTO -> {
                TaskSimpleResponse taskSimpleResponse = new TaskSimpleResponse();
                BeanUtils.copyProperties(taskSimpleDTO, taskSimpleResponse);
                taskSimpleResponses.add(taskSimpleResponse);
            });

            ResearchDTO researchDTO = researchService.findResearchNormalById(researchId);

            BeanUtils.copyProperties(researchDTO, researchNormalResponse);
            researchNormalResponse.setTaskSimpleResponseList(taskSimpleResponses);
            researchNormalResponse.setDocumentSimpleResponseList(documentSimpleResponses);

            userResearchDTOS.forEach(userResearchDTO -> {
                UserApplyResearchResponse userApplyResearchResponse = new UserApplyResearchResponse();
                BeanUtils.copyProperties(userResearchDTO, userApplyResearchResponse);
                userApplyResearchResponses.add(userApplyResearchResponse);
            });

            return CommonResponse.create(researchResponse);
        } catch (BadTokenException badTokenException) {
            badTokenException.printStackTrace();
        }
        return CommonResponse.Failed();
    }

    /**
     * 删除课题
     *
     * @param researchId
     * @return
     */
    @AnonymousPostMapping(value = "/delete")
    public CommonResponse deleteResearch(@RequestParam("researchId") Integer researchId) {
        try {
            researchService.deleteResearch(researchId);
            userResearchService.deleteUserResearch(researchId);
            keywordResearchService.deleteKeywordByResearchId(researchId);
            taskService.deleteTaskByResearchId(researchId);
        } catch (BadRequestException e) {
            e.printStackTrace();
            System.out.println(e.getError());
            return CommonResponse.Failed();
        }
        return CommonResponse.create(CommonResponse.STATUS_SUCCESS);
    }

    /**
     * 用户申请加入课题
     *
     * @param userApplyResearchRequest
     * @return
     */
    @AnonymousGetMapping(value = "/manageResearchUser")
    public CommonResponse manageResearchUser(@RequestBody UserApplyResearchRequest userApplyResearchRequest) {
        try {
            researchService.userApplyResearch(userApplyResearchRequest.getUserId(), userApplyResearchRequest.getResearchId(), userApplyResearchRequest.getRemark());
        } catch (BadRequestException badRequestException) {
            badRequestException.printStackTrace();
            return CommonResponse.Failed();
        }
        return CommonResponse.create(CommonResponse.STATUS_SUCCESS);

    }


    /**
     * 查看课题下所有用户
     *
     * @param researchId
     * @return
     */
    @AnonymousGetMapping(value = "/Users")
    public CommonResponse findAllResearchUsers(@RequestParam("researchId") Integer researchId) {
        try {
            List<UserResearchDTO> userResearchDTOS = userResearchService.findUsersByresearch(researchId);

            List<ResearchUserResponse> researchResponses = new LinkedList<>();

            userResearchDTOS.forEach(userResearchDTO -> {
                ResearchUserResponse researchUserResponse = new ResearchUserResponse();
                BeanUtils.copyProperties(userResearchDTO, researchUserResponse);
                String imgurlid = sysUserService.getById(userResearchDTO.getUserId()).getUserImg();
                researchUserResponse.setUserName(sysUserService.getById(userResearchDTO.getUserId()).getName());
                researchUserResponse.setUserImgId(imgurlid);
                researchUserResponse.setImgName(fileService.getById(Integer .parseInt(imgurlid)).getFileName());
                researchResponses.add(researchUserResponse);
            });
            return CommonResponse.create(researchResponses);

        } catch (BadTokenException badTokenException) {
            badTokenException.printStackTrace();
        }
        return CommonResponse.Failed();
    }

    /**
     * 根据关键词获取课题
     *
     * @param keywords
     * @return
     */
    @AnonymousGetMapping(value = "/ResearchByKeywords")
    public CommonResponse findResearchSimpleByKeywords(@RequestParam("keywords") String keywords) {
        List<ResearchSimpleDTO> researchSimpleDTOS = researchService.findResearchByKeyword(keywords);

        List<ResearchSimpleResponse> researchSimpleResponses = new LinkedList<>();

        researchSimpleDTOS.forEach(researchSimpleDTO -> {
            if (researchSimpleDTO.getResearchId() != 0) {
                ResearchSimpleResponse researchSimpleResponse = new ResearchSimpleResponse();
                BeanUtils.copyProperties(researchSimpleDTO, researchSimpleResponse);
                researchSimpleResponses.add(researchSimpleResponse);
            }
        });

        return CommonResponse.create(researchSimpleResponses);
    }

    @AnonymousGetMapping(value = "/ResearchesInGroup")
    public CommonResponse findResearchSimpleByGroupId(@RequestParam("researchGroupId") Integer researchGroupId) {
        List<ResearchSimpleDTO> researchSimpleDTOS = researchService.findResearchByResearchGroupId(researchGroupId);

        List<ResearchSimpleResponse> researchSimpleResponses = new LinkedList<>();

        researchSimpleDTOS.forEach(researchSimpleDTO -> {
            if (researchSimpleDTO.getResearchId() != 0) {
                ResearchSimpleResponse researchSimpleResponse = new ResearchSimpleResponse();
                BeanUtils.copyProperties(researchSimpleDTO, researchSimpleResponse);
                researchSimpleResponses.add(researchSimpleResponse);
            }
        });

        return CommonResponse.create(researchSimpleResponses);
    }

    @AnonymousGetMapping(value = "/applylist")
    public CommonResponse findUsersSimpleByResearchId(@RequestParam("researchId") Integer researchId) {
        try {
            List<UserResearchDTO> userResearchDTOS = userResearchService.findApplyUsersByresearch(researchId);

            List<ResearchUserResponse> researchResponses = new LinkedList<>();

            userResearchDTOS.forEach(userResearchDTO -> {
                ResearchUserResponse researchUserResponse = new ResearchUserResponse();
                BeanUtils.copyProperties(userResearchDTO, researchUserResponse);
                String imgurlid = sysUserService.getById(userResearchDTO.getUserId()).getUserImg();
                researchUserResponse.setUserName(sysUserService.getById(userResearchDTO.getUserId()).getName());
                researchUserResponse.setUserImgId(imgurlid);
                researchUserResponse.setImgName(fileService.getById(Integer .parseInt(imgurlid)).getFileName());
                researchResponses.add(researchUserResponse);
            });
            return CommonResponse.create(researchResponses);

        } catch (BadTokenException badTokenException) {
            badTokenException.printStackTrace();
        }
        return CommonResponse.Failed();
    }

    @AnonymousPostMapping(value = "/pass")
    public CommonResponse passUserApply(@RequestParam("researchId") Integer researchId, @RequestParam("userId") Integer userId) {
        try {
            Integer count = userResearchService.PassApplyUsersByResearch(researchId, userId);

            return CommonResponse.create(count);

        } catch (BadTokenException badTokenException) {
            badTokenException.printStackTrace();
            System.out.println(badTokenException.getData());
        }
        return CommonResponse.Failed();
    }

    @AnonymousPostMapping(value = "/reject")
    public CommonResponse rejectUserApply(@RequestParam("researchId") Integer researchId, @RequestParam("userId") Integer userId) {
        try {
            Integer count = userResearchService.RejectApplyUsersByResearch(researchId, userId);

            return CommonResponse.create(count);

        } catch (BadTokenException badTokenException) {
            badTokenException.printStackTrace();
            System.out.println(badTokenException.getData());
        }
        return CommonResponse.Failed();
    }
}